import { Radar } from 'react-chartjs-2'
import './setup' // 确保Chart.js组件被注册
import { colors } from './chartConfig'
import { getCategoryLabel } from '../../utils'

interface EfficiencyData {
  avgCompletionDays: number
  delayRate: number
  categoryEfficiency: Array<{
    category: string
    avgDays: number
    completedCount: number
  }>
  totalCompletedTasks: number
}

interface EfficiencyRadarChartProps {
  data: EfficiencyData
}

export default function EfficiencyRadarChart({ data }: EfficiencyRadarChartProps) {
  if (!data.categoryEfficiency || data.categoryEfficiency.length === 0) {
    return (
      <div className="h-64 flex items-center justify-center text-theme-text-muted">
        <div className="text-center">
          <div className="w-16 h-16 bg-theme-bg-tertiary rounded-full flex items-center justify-center mx-auto mb-3">
            🎯
          </div>
          <p>暂无效率数据</p>
        </div>
      </div>
    )
  }

  // 如果数据点少于3个，显示简化的条形图
  if (data.categoryEfficiency.length < 3) {
    return (
      <div className="h-64 flex items-center justify-center">
        <div className="text-center space-y-4 w-full max-w-sm">
          <div className="text-sm font-medium text-theme-text-secondary mb-4">分类效率对比</div>
          {data.categoryEfficiency.map((cat) => {
            const efficiency = Math.max(10, Math.min(100, 100 - (cat.avgDays * 10) + (cat.completedCount * 3)))
            return (
              <div key={cat.category} className="space-y-2">
                <div className="flex justify-between items-center">
                  <span className="text-sm text-theme-text-secondary">{getCategoryLabel(cat.category)}</span>
                  <span className="text-sm font-semibold text-blue-600">{Math.round(efficiency)}%</span>
                </div>
                <div className="w-full bg-slate-200 rounded-full h-3">
                  <div
                    className="bg-gradient-to-r from-blue-500 to-blue-600 h-3 rounded-full transition-all duration-1000 ease-out"
                    style={{ width: `${efficiency}%` }}
                  ></div>
                </div>
                <div className="text-xs text-theme-text-muted">
                  平均 {cat.avgDays} 天 · {cat.completedCount} 个任务
                </div>
              </div>
            )
          })}
        </div>
      </div>
    )
  }

  // 创建标准化的雷达图数据（至少3个维度）
  const radarDimensions = [
    { label: '完成速度', getValue: (cat: any) => Math.max(10, 100 - (cat.avgDays * 15)) },
    { label: '任务数量', getValue: (cat: any) => Math.min(100, cat.completedCount * 10) },
    { label: '综合效率', getValue: (cat: any) => Math.max(20, 100 - (cat.avgDays * 8) + (cat.completedCount * 2)) }
  ]

  // 计算每个分类的平均得分
  const categoryScores = data.categoryEfficiency.slice(0, 5).map(cat => ({
    category: cat.category,
    scores: radarDimensions.map(dim => Math.min(100, Math.max(0, dim.getValue(cat))))
  }))

  const chartData = {
    labels: radarDimensions.map(dim => dim.label),
    datasets: categoryScores.map((cat, index) => {
      const colorIndex = index % Object.keys(colors).length
      const colorKeys = Object.keys(colors) as (keyof typeof colors)[]
      const color = colors[colorKeys[colorIndex]]
      
      return {
        label: getCategoryLabel(cat.category),
        data: cat.scores,
        backgroundColor: color.bg.replace('0.8', '0.1'),
        borderColor: color.border,
        borderWidth: 2,
        pointBackgroundColor: color.border,
        pointBorderColor: '#ffffff',
        pointBorderWidth: 2,
        pointRadius: 3,
        pointHoverRadius: 5
      }
    })
  }

  const options = {
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
      legend: {
        position: 'bottom' as const,
        labels: {
          usePointStyle: true,
          padding: 15,
          font: {
            size: 11
          }
        }
      },
      tooltip: {
        backgroundColor: 'rgba(15, 23, 42, 0.9)',
        titleColor: '#f8fafc',
        bodyColor: '#f8fafc',
        borderColor: 'rgba(148, 163, 184, 0.2)',
        borderWidth: 1,
        cornerRadius: 8,
        padding: 12,
        callbacks: {
          title: (context: any) => {
            return `${context[0].dataset.label}`
          },
          label: (context: any) => {
            const dimension = radarDimensions[context.dataIndex]
            const score = Math.round(context.parsed.r)
            return `${dimension.label}: ${score}/100`
          }
        }
      }
    },
    scales: {
      r: {
        beginAtZero: true,
        max: 100,
        min: 0,
        ticks: {
          stepSize: 25,
          color: '#64748b',
          font: {
            size: 9
          },
          callback: function(value: any) {
            return value === 0 ? '' : value
          },
          backdropColor: 'transparent'
        },
        grid: {
          color: 'rgba(148, 163, 184, 0.15)',
          lineWidth: 1
        },
        angleLines: {
          color: 'rgba(148, 163, 184, 0.2)',
          lineWidth: 1
        },
        pointLabels: {
          color: '#475569',
          font: {
            size: 11,
            weight: 'normal' as const
          }
        }
      }
    },
    animation: {
      duration: 1500,
      easing: 'easeOutQuart' as const
    },
    elements: {
      point: {
        radius: 3,
        hoverRadius: 5,
        borderWidth: 2
      },
      line: {
        borderWidth: 2,
        tension: 0.2
      }
    }
  }

  return (
    <div className="h-64">
      <Radar data={chartData} options={options} />
    </div>
  )
}
